import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_scan_tool/db/dio_manage.dart';
import 'package:flutter_scan_tool/models/ToolImage.dart';
import 'package:flutter_scan_tool/models/ToolLog.dart';
import 'package:flutter_scan_tool/models/storage_info.dart';
import 'package:flutter_scan_tool/models/tool.dart';
class ApiProvider {
  static const successCode = 200;

  static Future<List<ToolData>> fetchToolList(Map<String, dynamic> maps) async {
    try {
      Map<String, dynamic> response =
          await DioManager().post(url: '/module/lockerDict/lockerTools', params: maps);
      return parseResponse(response);
    } catch (err) {
      debugPrint(err.toString());
      return [];
    }
  }

  static Future<List<ToolImage>> fetchToolImageList() async {
    try{
      Map<String,dynamic> response=await DioManager().get(url: "/module/toolVsImg/queryAll", params: {});
      if(response['code']==successCode){
        List arrayList=response['data'] as List;
        List<ToolImage> list=arrayList.map((e) => ToolImage.fromJson(jsonEncode(e))).toList();
        return list;
      }else{
        throw Exception(response['message']);
      }
    }catch(err){
      throw Exception(err);
    }
  }

  static Future<List<ToolLog>> fetchToolLogList(String toolId) async {
    try {
      Map<String, dynamic> response = await DioManager()
          .get(url: '/module/toolLogs/logs?toolId=$toolId', params: {});
      if (response['code'] == successCode) {
        List arrayJson = response['data'] as List;
        List<ToolLog> list =
            arrayJson.map((e) => ToolLog.fromJson(jsonEncode(e))).toList();
        return list;
      } else {
        throw Exception('请求失败');
      }
    } catch (err) {
      return [];
    }
  }

  static List<ToolData> parseResponse(Map<String, dynamic> response) {
    if (response['code'] == successCode) {
      List item1 = response['data'] as List;
      List<ToolData> toolList =
          item1.map((e) => ToolData.fromJson(jsonEncode(e))).toList();
      return toolList;
    } else {
      return [];
    }
  }

  static Future<List<StorageInfo>> getStorageList() async {
    try {
      Map<String, dynamic> response =
          await DioManager().get(url: '/module/storageDict/queryAllLockerList', params: {});
      if (response['code'] == successCode) {
        List storageList = response['data'] as List;
        return storageList
            .map((e) => StorageInfo.fromJson(json.encode(e)))
            .toList();
      } else {
        throw Exception('获取错误');
      }
    } catch (err) {
      debugPrint(err.toString());
      return [];
    }
  }
}
